const router = require('express').Router();
const joi = require('joi');
const joiValidate = require('../../../utils/joiValidate');
const courseService = require('../../../service/user/courseService');
const verifyUser = require('../../../utils/jwtHanlder');
const LockUtil = require('../../../utils/lockUtil');
const ErrorCode = require('../../../utils/errorCode');

/**
 * @api {get} /v1/user/course/list  获取用户的课程列表
 * @apiVersion 1.0.0
 * @apiName UserCourseList
 * @apiGroup  User
 *
 * @apiDescription 获取用户的课程列表 （获取用户的课程列表）
 *
 * @apiParam {number=0,1,2} querystatus 课程状态（0代表全部，1代表未完结，10代表完结）
 * @apiParam {Number} [offset]  分页参数
 * @apiParam {Number} [limit]  分页参数
 * @apiParam {Number} [queryuid]  要查看的的用户
 * @apiParam {Number} [type]  类别
 * @apiParam {Number} [isBuy]  0或者1 1代表教练查看自己购买的课程
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/user/course/list
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 * @apiSuccess {Object} data    结果集对象
 * @apiSuccess {Object} data.list    结果集对象
 * @apiSuccess {Number} data.list.type    类别(课程类别)
 * @apiSuccess {Number} data.list.id    课程Id
 * @apiSuccess {String} data.list.courseName    课程名称
 * @apiSuccess {Number} data.list.classNum    课时节数
 * @apiSuccess {String} data.list.startTime    开始时间
 * @apiSuccess {Number} data.list.classTime    课程时间
 * @apiSuccess {Number} data.list.totalMoney    金额
 * @apiSuccess {Number} data.list.peopleNum    人数
 * @apiSuccess {Number} data.list.cStatus    状态(1是未完结，10是已完结)
 * @apiSuccess {String} data.list.label    标签
 * @apiSuccess {String} data.list.description    描述
 * @apiSuccess {Object} data.list.images    图片(数组，所有的图片，可以取第一条，需要判断下第一条是否有)
 * @apiSuccess {String} data.list.images.imagePath   图片路劲
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 *     {
          "code": 200,
          "message": "请求成功"
          "data": {
            "list": [
                {
                    "type": 1,
                    "id": 1,
                    "courseName": "xxx",
                    "classNum": 12,
                    "startTime": "2019-06-08 17:07:04",
                    "classTime": 32,
                    "totalMoney": "12.00",
                    "peopleNum": 3,
                    "label": "xxx",
                    "storeName": "xx",
                    "description": "fds",
                    "JUserId": 8,
                    "images": [
                        {
                            "courseId": 1,
                            "imagePath": "http://xiaoqingjing.oss-cn-beijing.aliyuncs.com/tyk/wxcbbe76597beeacf1.o6zAJs4-ejA5oZd4Y8LttNODu5Go.OC4tW5NgmWfe5cb23895f97d7edbc59937059b0740e2.jpg"
                        }
                    ]
                }
            ],
            "count": 1
            }
       }
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.get('/list', verifyUser.verifyHasToken(), joiValidate(joi.object().keys({
  querystatus: joi.number().valid([0,1,10]).required().label('请选择课程状态'),
  offset: joi.number().label('请传入分页参数'),
  limit: joi.number().label('请传入分页参数'),
  queryuid: joi.number().label('请传入查询用户的id'),
  type: joi.number().valid([0,1,2,3]).label('请传入查询用户的id'),
  isBuy: joi.number().label('请传入是否是教练自己查询自己购买的课程')
})), (req, res, next) => {
  const { querystatus, offset, limit, queryuid, type, isBuy } = req.query;
  const { userId } = req.user;

  courseService.getList({ querystatus, offset, limit, userId, queryuid, type, isBuy })
    .then((data) => res.success(data))
    .catch(e => next(e))
});

/**
 * @api {get} /v1/user/course/clist  获取用户的确认课程列表
 * @apiVersion 1.0.0
 * @apiName UserCourseConfirmList
 * @apiGroup  User
 *
 * @apiDescription 获取用户的确认课程列表
 *
 * @apiParam {number=0,1,-1} status （0代表待确认，1代表已确认，-1已拒绝）
 * @apiParam {Number} [offset]  分页参数
 * @apiParam {Number} [limit]  分页参数
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/user/course/clist
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 * @apiSuccess {Object} data    结果集对象
 * @apiSuccess {Object} data.list    结果集对象
 * @apiSuccess {Number} data.list.type    类别(课程类别)
 * @apiSuccess {Number} data.list.id    课程Id
 * @apiSuccess {String} data.list.courseName    课程名称
 * @apiSuccess {Number} data.list.classNum    课时节数
 * @apiSuccess {String} data.list.startTime    开始时间
 * @apiSuccess {Number} data.list.classTime    课程时间
 * @apiSuccess {Number} data.list.totalMoney    金额
 * @apiSuccess {Number} data.list.peopleNum    人数
 * @apiSuccess {Number} data.list.status    （状态值）
 * @apiSuccess {String} data.list.label    标签
 * @apiSuccess {String} data.list.description    描述
 * @apiSuccess {Object} data.list.images    图片(数组，所有的图片，可以取第一条，需要判断下第一条是否有)
 * @apiSuccess {String} data.list.images.imagePath   图片路劲
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 {
    "code": 200,
    "message": "请求成功",
    "data": {
        "list": [
            {
                "type": 1,
                "id": 29,
                "courseName": "团课1",
                "classNum": 0,
                "startTime": "08-17 09:01",
                "classTime": 45,
                "totalMoney": "1.00",
                "peopleNum": 49,
                "label": "团课1",
                "storeName": "上海上海阿萨德路恢复萨肯德基",
                "description": "阿斯顿发送到发送到发的说法第三方法第三方咋说打色粉ZS打发斯蒂芬啊实打实",
                "JUserId": 11,
                "images": [
                    {
                        "courseId": 29,
                        "imagePath": "http://xiaoqingjing.oss-cn-beijing.aliyuncs.com/tyk/wx814d8e19f0064f25.o6zAJs4-ejA5oZd4Y8LttNODu5Go.SXPFnGgE44jOb0b0b7f0a39aec180accc705353b1a40.jpg"
                    }
                ],
                "status": 0
            }
        ],
        "count": 1
    }
}
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.get('/clist', verifyUser.verify(), joiValidate(joi.object().keys({
  status: joi.number().valid([1,-1,0]).required().label('请输入查询的状态'),
  offset: joi.number().label('请传入分页参数'),
  limit: joi.number().label('请传入分页参数')
})), (req, res, next) => {
  let { status, offset, limit } = req.query;
  offset = offset && Number(offset) || 0;
  limit = limit && Number(limit) || 20;
  const { userId } = req.user;
  courseService.getUserConfirmList({ offset, limit, status, userId })
    .then((data) => res.success(data))
    .catch(e => next(e))
});

/**
 * @api {post} /v1/user/course/subscribe  用户预约课程
 * @apiVersion 1.0.0
 * @apiName UserCourseSubscribe
 * @apiGroup  User
 *
 * @apiDescription 用户预约课程(预约)
 *
 * @apiParam {number} courseId 课程Id
 * @apiParam {Number} campId  课时Id
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/user/course/subscribe
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 *     {
          "code": 200,
          "message": "请求成功"
       }
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.post('/subscribe', verifyUser.verify(), joiValidate(joi.object().keys({
  courseId: joi.number().required().label('请选择要预约的课程'),
  campId: joi.number().allow('', null).label('请选择要预约的课时Id')
})), (req, res, next) => {
  // todo 操作记录
  const { userId } = req.user;
  const { campId, courseId } = req.body;
  const lockUtil = new LockUtil(`course:subscribe:${userId}:`, courseId , 120);
  return lockUtil.tryLock()
    .then(() => courseService.subscribe({ courseId, campId, userId }))
    .then(() => {
      // 删除请求锁
      lockUtil.unlock().catch(console.error);
      res.success();
    })
    .catch((err) => {
      // 非频繁访问时删除频繁队列key
      if (err.code !== ErrorCode.FREQUENT_REQUEST) lockUtil.unlock().catch(console.error);
      next(err);
    });
});

/**
 * @api {post} /v1/user/course/confirm  用户确认课程
 * @apiVersion 1.0.0
 * @apiName UserCourseConfirm
 * @apiGroup  User
 *
 * @apiDescription 用户确认课程
 *
 * @apiParam {number} courseId 课程Id
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/user/course/confirm
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 *     {
          "code": 200,
          "message": "请求成功"
       }
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.post('/confirm', verifyUser.verify(), joiValidate(joi.object().keys({
  courseId: joi.number().required().label('请选择要确认的课程')
})), (req, res, next) => {
  // todo 操作记录
  const { courseId } = req.body;
  const { userId } = req.user;
  const lockUtil = new LockUtil(`course:confirm:${userId}:`, courseId , 120);
  return lockUtil.tryLock()
    .then(() =>   courseService.confirm({ courseId, userId }))
    .then(() => {
      // 删除请求锁
      lockUtil.unlock().catch(console.error);
      res.success();
    })
    .catch((err) => {
      // 非频繁访问时删除频繁队列key
      if (err.code !== ErrorCode.FREQUENT_REQUEST) lockUtil.unlock().catch(console.error);
      next(err);
    });
});

/**
 * @api {post} /v1/user/course/unsubscribe  用户取消预约课程
 * @apiVersion 1.0.0
 * @apiName UserCourseUnSubscribe
 * @apiGroup  User
 *
 * @apiDescription 用户取消预约课程
 *
 * @apiParam {number} courseId 课程Id
 * @apiParam {Number} campId  课时Id
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/user/course/unsubscribe
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 *     {
          "code": 200,
          "message": "请求成功"
       }
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.post('/unsubscribe', verifyUser.verify(), joiValidate(joi.object().keys({
  courseId: joi.number().required().label('请选择要预约的课程'),
  campId: joi.number().allow('', null).label('请选择要预约的课时Id'),
  remark: joi.string().label('请填入退款原因')
})), (req, res, next) => {
  // todo 操作记录
  const {courseId, campId, remark}  = req.body;
  const { userId } = req.user;
  const lockUtil = new LockUtil(`course:unsubscribe:${userId}:`, courseId , 120);
  return lockUtil.tryLock()
    .then(() => courseService.unSubscribe({ courseId, userId, remark }))
    .then(() => {
      // 删除请求锁
      lockUtil.unlock().catch(console.error);
      res.success();
    })
    .catch((err) => {
      // 非频繁访问时删除频繁队列key
      if (err.code !== ErrorCode.FREQUENT_REQUEST) lockUtil.unlock().catch(console.error);
      next(err);
    });
});

module.exports = router;
